package com.huali.pattern.prototype.deepclone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class DeepProtoType implements Serializable, Cloneable {

	public String name;
	public DeepCloneableTarget deepCloneableTarget;

	public DeepProtoType() {
		super();
	}

	// 方式1
	@Override
	protected Object clone() throws CloneNotSupportedException {
		Object deep = null;
		deep = super.clone();
		DeepProtoType deepProtoType = (DeepProtoType) deep;
		deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

		return deepProtoType;
	}

	// 方式2 使用序列化
	public Object deepClone() {
		try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(bos);
				ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
				ObjectInputStream ois = new ObjectInputStream(bis)) {

			// 序列化
			oos.writeObject(this);

			// 反序列化
			DeepProtoType copyObj = (DeepProtoType) ois.readObject();
			return copyObj;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
